<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 用户管理管理
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{
    public $WX_APPID = 'wx6f8f0af9f1aa443a';

    public $WX_APPSECRET = 'f5a3d356ced0a028c91260222500d088';
    /**
     * Member模型对象
     * @var \app\admin\model\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Member;
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("authenStatusList", $this->model->getAuthenStatusList());
        $this->view->assign("recStatusList", $this->model->getRecStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {   
        $id = input('param.ids');
        if($id){
            $gender = db('member')->where(['id'=>$id])->value('gender');
            $mate = db('mate')->where(['uid'=>$id])->group('mate_uid')->select();
            $mate_ids = [];
            if($mate){
                foreach ($mate as $key => $value) {
                   $mate_ids[] = $value['mate_uid'];
                }
            }
            if($gender == 0){
                $map['gender'] = 1;
            }else{
                $map['gender'] = 0;
            }
            $map['member.id'] = array('not in',$mate_ids);
        }else{
            $map = true;
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //dump($map);
            $total = $this->model
                    ->with(['car','house','income','education','marriage','zodiac','tags'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['car','house','income','education','marriage','zodiac','tags'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            //dump($list);exit;

            foreach ($list as $row) {
                $row->visible(['id','user_name','birthday','age','height','mobile','wechat','avatar','gender','birth_city','live_city','authen_status','rec_status','create_time','headimgurl','wechat_name','is_mate']);
                $row->visible(['car']);
				$row->getRelation('car')->visible(['name']);
				$row->visible(['house']);
				$row->getRelation('house')->visible(['name']);
				$row->visible(['income']);
				$row->getRelation('income')->visible(['name']);
				$row->visible(['education']);
				$row->getRelation('education')->visible(['name']);
				$row->visible(['marriage']);
				$row->getRelation('marriage')->visible(['name']);
				$row->visible(['zodiac']);
				$row->getRelation('zodiac')->visible(['name']);
				$row->visible(['tags']);
				$row->getRelation('tags')->visible(['title']);
            }
            $list = collection($list)->toArray();
            foreach ($list as $key => &$value) {
                $mate_info = db('member_mate')->where(['uid'=>$value['id']])->find();
                if($mate_info){
                    $value['mate_age'] = db('age')->where(['id'=>$mate_info['age_id']])->value('name');
                    $value['mate_height'] = db('height')->where(['id'=>$mate_info['height_id']])->value('name');
                    $value['mate_marriage'] = db('marriage')->where(['id'=>$mate_info['marriage_id']])->value('name');
                    $value['mate_education'] = db('education')->where(['id'=>$mate_info['education_id']])->value('name');
                }else{
                    $value['mate_age'] = '';
                    $value['mate_height'] = '';
                    $value['mate_marriage'] = '';
                    $value['mate_education'] = '';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('id',$id);
        return $this->view->fetch();
    }

    /**
     * 匹配
     */
    public function mate(){
        $mate_uid = input('param.ids');
        $uid = trim(input('param.from_uid'));
        if($uid=="null"){
            $info2= db('member')->where(['id'=>$mate_uid])->find();
            $openid2 = $info2['openid'];
            $re = $this->send($openid2,'失败','请修改择偶条件,有利于快速匹配！');
            db('member')->where(['id'=>$mate_uid])->update(['is_mate'=>2]);
            return json(['msg'=>'匹配失败!','code'=>1]);
        }
        $data1 = [
            'uid' => $uid,
            'mate_uid' => $mate_uid,
            'create_time' => time(),
        ];
        //dump($data1);exit;
        $re1 = db('mate')->insert($data1);
        if($re1){
            $info1 = db('member')->where(['id'=>$uid])->find();
            $openid1 = $info1['openid'];
            db('member')->where(['id'=>$uid])->update(['is_mate'=>2]);
            $re = $this->send($openid1,'成功','你有一条新的匹配信息，请前我的匹配列表往查看！');       }
        $data2 = [
            'uid' => $mate_uid,
            'mate_uid' => $uid,
            'create_time' => time(),
        ];
        $re2 = db('mate')->insert($data2);
        if($re2){
            $info2= db('member')->where(['id'=>$mate_uid])->find();
            $openid2 = $info2['openid'];
            $re = $this->send($openid2,'成功','你有一条新的匹配信息，请前我的匹配列表往查看！');
            db('member')->where(['id'=>$mate_uid])->update(['is_mate'=>2]);
        }
        return json(['msg'=>'匹配成功!','code'=>1]);
    }

    /**
     * 获取token
     * @return [type] [description]
     */
    public function get_accesstoken(){
        $access_token_info = json_decode(file_get_contents('access_token.json'),true);
        $expires_time = time()+3600;
        if($access_token_info){
            if($access_token_info['expires_time']<time()){
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_APPSECRET;
                $geturl = geturl($url);
                file_put_contents('access_token.json', '{"access_token": "'.$geturl['access_token'].'","expires_time": '.$expires_time.'}');
                return $geturl['access_token'];
            }else{
                return $access_token_info['access_token'];
            }
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_APPSECRET;
            $geturl = geturl($url);
            file_put_contents('access_token.json', '{"access_token": "'.$geturl['access_token'].'","expires_time": '.$expires_time.'}');
            return $geturl['access_token'];
        }
        
    }

    /**
     * 发送消息
     * @return [type] [description]
     */
    public function send($openid,$keyword2,$remark){
        //$openid = 'ooP9N1FJVgesQo5RCTfbT0zEYox0';
        $token = $this->get_accesstoken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}";
        $post_data['touser'] = $openid;
        $post_data['template_id'] = "T-iul539F8FUDiaaULKefcXNVqMWOjtn2ZqkIKIzGro";
        $post_data['data'] = array(
            "first"=>array(
              "value"=>"匹配成功通知"
            ),
            "keyword1"=>array(
              "value"=>'匹配对象'
            ),
            "keyword2"=>array(
              "value"=>$keyword2
            ),
            "keyword3"=>array(
              "value"=>date('Y-m-d H:i:s',time())
            ),
            "remark"=>array(
              "value"=>$remark
            )
        );
        $res = posturl($url,json_encode($post_data));
        return $res;
    }
}
